package org.idea.iedis.framework.server.dict;

import org.idea.iedis.framework.server.datastruct.string.EntryVal;
import org.idea.iedis.framework.server.datastruct.string.Sds;

import static org.idea.iedis.framework.server.datastruct.DataStructTypeConstants.STRING;

/**
 * iedis的基础，用于存储key，哈希结构
 *
 * @Author linhao
 * @Date created in 11:38 上午 2021/4/30
 */
public class Dict {

    private HashMap[] dictHt = new HashMap[2];

    private float threadSize = 0.75f;

    private float defaultEnlargeSize = 1.5f;


    public Dict() {
        dictHt[0] = new HashMap<String, String>();
        dictHt[1] = new HashMap<String, String>();
    }

    public void rehash() {
        int u = dictHt[0].getUseSize();
        if (u > dictHt[0].getCurrentSize() * this.threadSize) {
            int newSize = (int) (dictHt[0].getCurrentSize() * defaultEnlargeSize);
            this.doRehash(newSize);
            System.out.println("rehash 结束");
        }
    }

    public void addSds(String key, String value) {
        this.dictHt[0].put(key, new EntryVal(STRING, new Sds(value)));
        this.rehash();
    }

    public void display() {
        Entry<String, EntryVal>[] entryValEntry = this.dictHt[0].getTable();
        for (int i = 0; i < entryValEntry.length; i++) {
            Entry<String, EntryVal> item = entryValEntry[i];
            if (item == null) {
                continue;
            }
            while (item != null) {
                EntryVal entryVal = item.getVal();
                String key = item.getKey();
                System.out.println("key:" + key + " , value:" + entryVal);
                item = item.getNext();
            }
        }
    }

    private void doRehash(int newSize) {
        HashMap<String, EntryVal> currentMap = dictHt[0];
        dictHt[1] = new HashMap(newSize);
        HashMap<String, EntryVal> newMap = dictHt[1];
        Entry<String, EntryVal>[] entryValEntry = currentMap.getTable();
        for (int i = 0; i < entryValEntry.length; i++) {
            Entry<String, EntryVal> item = entryValEntry[i];
            if (item == null) {
                continue;
            }
            while (item != null) {
                EntryVal entryVal = item.getVal();
                String key = item.getKey();
                newMap.put(key, entryVal);
                item = item.getNext();
            }
        }
        dictHt[0] = dictHt[1];
        dictHt[1] = null;
    }


}
